package com.wuseguang.springcloud.controller;


import com.wuseguang.springcloud.JdbcTemplate.BaseTemplate;
import com.wuseguang.springcloud.JdbcTemplate.WXJdbc;
import com.wuseguang.springcloud.dao.repository.ParentRepository;
import com.wuseguang.springcloud.dao.repository.StudentRepository;
import com.wuseguang.springcloud.entity.Parent;
import com.wuseguang.springcloud.service.StudentService;
import com.wuseguang.springcloud.util.*;
import com.wuseguang.springcloud.util.WeChat.WXUtil;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 * 学生表 前端控制器
 * </p>
 *
 * @author
 * @since 2019-12-29
 */
@RestController

public class StudentController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private StudentService studentServiceImpl;
    @Autowired
    private StudentRepository studentRepository;
    @Autowired
    private BaseTemplate baseTemplate;
    @Autowired
    private ParentRepository parentRepository;


    /**
     * 家长登录
     *
     * @param response
     * @param phone    手机号码
     * @param pwd      密码
     * @param type     登录类型 0 web登录，1小程序登录
     * @param code 小程序code
     * @return
     */
    @RequestMapping("/plogin")
    public Result plogin(HttpServletResponse response,
                         @RequestParam("phone") String phone,
                         @RequestParam("pwd") String pwd,
                         @RequestParam(value = "type", defaultValue = "0") Integer type,
                         @RequestParam(value = "code",required = false) String code) {

        //判断手机号码是否为空
        if (StringUtils.isEmpty(phone)) {
            logger.info("mobile is null");
            return new Result(CodeUtil.MOBILE_IS_NULL);
        }
        //判断密码是否为空
        if (StringUtils.isEmpty(pwd)) {
            logger.info("pwd is null");
            return new Result(CodeUtil.PWD_IS_NULL);
        }
        Parent parent = null;
        try{
            parent =   parentRepository.findByPhone(phone);
        }catch (IncorrectResultSizeDataAccessException e){
            return new Result(CodeUtil.THERE_ARE_DUPLICATE_NUMBERS);
        }

        //判断如果手机号码为空
        if (parent == null) {
            List<Map<String, Object>> list = baseTemplate.queryListMap("SELECT id,student_name,phone FROM student WHERE phone=?", phone);
            if (list!=null&list.size()>1){
                return new Result(CodeUtil.THERE_ARE_DUPLICATE_NUMBERS);
            }

            if (list!=null&list.size()>0){
                Long aLong = baseTemplate.updateByParameterGetId("insert into `parent` (`phone`,`password`, `name`) values(?,?,?)", list.get(0).get("phone"),MyDES.encryptBasedDes(pwd) ,list.get(0).get("student_name") + "家长");
                if (aLong > 0) {
                    baseTemplate.updateByParameterGetId("insert into `parent_student` (`student_id`, `parent_id`) values(?,?)", list.get(0).get("id"),aLong);
                }
                parent =   parentRepository.findByPhone(phone);
            }else {
                logger.info("user does not exist");
                return new Result(CodeUtil.USER_DOES_NOT_EXIST);
            }
        }

        //判断密码是否正确
        if (!MyDES.decryptBasedDes(parent.getPassword()).equals(pwd)) {
            logger.info("password error");
            return new Result(CodeUtil.PASSWORD_ERROR);

        }

        //查询这个家长关联的学生信息
        String sql = "SELECT s.id, s.student_name,s.class_id,s.sex,s.head_portrait,s.school_id ,sc.school_name,c.name " +
                " FROM student s left join school sc on(s.school_id=sc.id) " +
                " LEFT join classes c on(s.class_id=c.id) " +
                " WHERE EXISTS ( SELECT * FROM parent_student ps WHERE ps.student_id = s.id AND ps.parent_id =? )";

        //查询学生数据(一个手机号只有一个学生)
        List<Map<String, Object>> list = baseTemplate.queryListMap(sql, parent.getId());

        if(!StringUtils.isEmpty(parent.getDueDate())){
            list.get(0).put("due_date", DateUtil.parseData(parent.getDueDate(),"yyyy-MM-dd"));
        }else {
            list.get(0).put("due_date", "");
        }

        String subject = String.format("%s-%s-%s-%s", parent.getId(), parent.getPhone(), parent.getName(),list.get(0).get("school_id"));

        //登录成功
        String token = Jwts.builder()
                .setSubject(subject)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + JWTUtils.EXPIRATION))
                .signWith(SignatureAlgorithm.HS512, JWTUtils.SIGNINGKEY)
                .compressWith(CompressionCodecs.DEFLATE)
                .compact();


        token = JWTUtils.STUDENT_PREFIX_VALIDATION + token;

        response.addHeader("token", token);
        Map<String, Object> hm = new HashMap<String, Object>();
        hm.put("token", token);
        hm.put("list", list);




        try {

            //判断如果为小程序登录并且小程序的openId为空
            if (type == 1&&!StringUtils.isEmpty(code)) {
                logger.info("小程序登录 code={}",code);
                //获取openId
                String  openId = WXUtil.getUserOpenId("wx30b606bac7775eba","a28468bfc8c9c7ed4277118f58beb85d",code);
                logger.info("获取的openId = {}",openId);
                if(!"error".equals(openId)){
                    parent.setOpenIdOne(openId);
                    parentRepository.save(parent);
                }
            }

        } catch (Exception e) {
            logger.error("获取用户openId失败", e);
        }

        return new Result(hm);
    }

}

